package com.yorick.logic.service;

import com.yorick.logic.entity.Account;
import com.yorick.logic.entity.Location;
import com.yorick.netty.WebSocketServerHandler;
import com.yorick.netty.utils.ServerUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.TimerTask;

@Slf4j
public class SyncScheduler extends TimerTask {

    @Override
    public void run() {
        for (Map.Entry<String, Location> entry : Account.locations.entrySet()) {
            com.yorick.logic.protobuf.Location.S2CLocation s2CLocation = com.yorick.logic.protobuf.Location.S2CLocation
                    .newBuilder()
                    .setAccount(entry.getKey())
                    .setX(entry.getValue().getX())
                    .setY(entry.getValue().getY())
                    .setR(entry.getValue().getR())
                    .build();
            channelSend(WebSocketServerHandler.channels,2, s2CLocation.toByteArray());
            log.info("account: {}, x: {}, y: {}, r: {}",
                    entry.getKey(),
                    entry.getValue().getX(),
                    entry.getValue().getY(),
                    entry.getValue().getR()
            );
        }
    }

    public void channelSend(ChannelGroup channel, int msg, byte[] body) {
        byte[] s_data = new byte[body.length + 6];
        byte[] s_id = ServerUtil.intToByteArray(msg);
        byte[] s_length = ServerUtil.short2Byte((short) body.length);
        System.arraycopy(s_length, 0, s_data, 0, s_length.length);
        System.arraycopy(s_id, 0, s_data, 2, s_id.length);
        System.arraycopy(body, 0, s_data, 6, body.length);
        ByteBuf resp = Unpooled.copiedBuffer(s_data);
        channel.writeAndFlush(new BinaryWebSocketFrame(resp));
    }
}
